package com.firebird.app.fekpsl.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.fragment.app.FragmentTransaction
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.app.App
import com.firebird.app.fekpsl.base.BaseMvpActivity
import com.firebird.app.fekpsl.constant.Constant
import com.firebird.app.fekpsl.event.LoginEvent
import com.firebird.app.fekpsl.event.RefreshHomeEvent
import com.firebird.app.fekpsl.ext.showToast
import com.firebird.app.fekpsl.mvp.home.MainContract
import com.firebird.app.fekpsl.bean.UserInfoBody
import com.firebird.app.fekpsl.mvp.home.MainPresenter
import com.firebird.app.fekpsl.ui.activity.common.CommonActivity
import com.firebird.app.fekpsl.ui.activity.exam.chinese.ExamChineseHomeActivity
import com.firebird.app.fekpsl.ui.activity.exam.english.ExamEnglishHomeActivity
import com.firebird.app.fekpsl.ui.activity.exam.mathematics.ExamMathematicsHomeActivity
import com.firebird.app.fekpsl.ui.activity.me.UpdateNiceNameActivity
import com.firebird.app.fekpsl.ui.activity.search.SearchActivity
import com.firebird.app.fekpsl.ui.activity.user.LoginActivity
import com.firebird.app.fekpsl.ui.fragment.*
import com.firebird.app.fekpsl.utils.DialogUtil
import com.firebird.app.fekpsl.utils.Preference
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.toolbar.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread

class MainActivity : BaseMvpActivity<MainContract.View, MainContract.Presenter>(), MainContract.View {

    private val BOTTOM_INDEX:String="bottom_index"

    private val FRAGMENT_HOME=0X01
    private val FRAGMENT_CLASSROOM = 0x02
    private val FRAGMENT_SWORD = 0x03
    private val FRAGMENT_DISCOVER = 0x04
    private val FRAGMENT_ME = 0x05

    private var mIndex = FRAGMENT_HOME

    private var mHomeFragment: HomeFragment? = null
    private var mClassroomFragment: ClassroomFragment? = null
    private var mSwordFragment: SwordFragment? = null
    private var mDiscoverFragment: DiscoverFragment? = null
    private var mMeFragment: MeFragment? = null

    private var mExitTime: Long = 0

    private var pf_user_name: String by Preference(Constant.USERNAME_KEY, "")
    private var pf_user_uuid:String by Preference(Constant.UUID_KEY, "")
    private var pf_nice_name:String by Preference(Constant.NICE_NAME_KEY, "")
    private var pf_real_name:String by Preference(Constant.REAL_NAME_KEY, "")
    private var pf_sex:Int by Preference(Constant.SEX_KEY, 1)
    private var pf_birthday:String by Preference(Constant.BIRTHDAY_KEY, "")
    private var pf_phone:String by Preference(Constant.PHONE_KEY, "")
    private var pf_avatar:String by Preference(Constant.AVATAR_KEY, "")
    private var pf_user_id:String by Preference(Constant.USER_ID_KEY, "")
    private var pf_email:String by Preference(Constant.EMAIL_KEY, "")
    private var pf_credit_score:Int by Preference(Constant.CREDIT_SCORE_KEY, 100)
    private var pf_area:String by Preference(Constant.AREA_KEY, "")
    private var pf_address:String by Preference(Constant.ADDRESS_KEY, "")
    private var pf_is_explicit:Int by Preference(Constant.IS_EXPLICIT_KEY, 1)
    private var pf_copper_cash:Long by Preference(Constant.COPPER_CASH_KEY, 0)
    private var pf_gold_ingot:Long by Preference(Constant.GOLD_INGOT_KEY, 0)
    private var pf_level_score:Long by Preference(Constant.LEVEL_SCORE_KEY, 0)

    override fun attachLayoutRes(): Int = R.layout.activity_main

    override fun createPresenter(): MainContract.Presenter = MainPresenter()

    override fun useEventBus(): Boolean = true

    override fun initData() {
       // Beta.checkUpgrade(false, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        if(savedInstanceState!=null){
            mIndex=savedInstanceState?.getInt(BOTTOM_INDEX)
        }
        super.onCreate(savedInstanceState)
    }

    override fun initView() {
        super.initView()
       /* toolbar.run {
            title = getString(R.string.app_name)
            setSupportActionBar(this)
        }*/

        bottom_navigation.run {
            // 以前使用 BottomNavigationViewHelper.disableShiftMode(this) 方法来设置底部图标和字体都显示并去掉点击动画
            // 升级到 28.0.0 之后，官方重构了 BottomNavigationView ，目前可以使用 labelVisibilityMode = 1 来替代
            // BottomNavigationViewHelper.disableShiftMode(this)
            labelVisibilityMode = 1
            setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
        }
       // img_exam_chinese.setOnClickListener(onClickListener)
        //img_exam_mathematics.setOnClickListener(onClickListener)
        //img_exam_english.setOnClickListener(onClickListener)

        initDrawerLayout()
       // initNavView()

        showFragment(mIndex)
    }

    /**
     * OnClickListener
     */
    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.img_exam_chinese -> {
                Intent(this@MainActivity, ExamChineseHomeActivity::class.java).run {
                    startActivity(this)
                }
            }
            R.id.img_exam_mathematics -> {
                Intent(this@MainActivity, ExamMathematicsHomeActivity::class.java).run {
                    startActivity(this)
                }
            }
            R.id.img_exam_english -> {
                Intent(this@MainActivity, ExamEnglishHomeActivity::class.java).run {
                    startActivity(this)
                }
            }
        }
    }

    override fun start() {
        // 获取用户个人信息
        mPresenter?.getUserInfo(pf_user_uuid)
    }

    override fun initColor() {
        //super.initColor()
        //refreshColor(ColorEvent(true))
    }

    /**
     * init DrawerLayout
     */
    private fun initDrawerLayout() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            var params = window.attributes
//            params.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
//            drawer_layout.fitsSystemWindows = true
//            drawer_layout.clipToPadding = false
//        }
        drawer_layout.run {
            val toggle = ActionBarDrawerToggle(
                    this@MainActivity,
                    this,
                    toolbar
                    , R.string.navigation_drawer_open,
                    R.string.navigation_drawer_close)
            addDrawerListener(toggle)
            toggle.syncState()
        }
    }

    /**
     * 显示用户信息，包括积分、等级、排名
     */
    override fun showUserInfo(bean: UserInfoBody) {
        App.userInfo = bean
        pf_user_name=bean.user_name
        pf_user_uuid=bean.user_uuid
        pf_nice_name=bean.nice_name
        pf_real_name=bean.real_name
        pf_sex=bean.sex
        pf_birthday=bean.birth_day.toString()
        pf_phone=bean.phone.toString()
        pf_avatar=bean.avatar_text.toString()
        pf_user_id=bean.user_id.toString()
        pf_email=bean.email.toString()
        pf_credit_score=bean.credit_score
        pf_area=bean.area.toString()
        pf_address=bean.address.toString()
        pf_is_explicit=bean.is_explicit
        pf_copper_cash=bean.copper_cash
        pf_gold_ingot=bean.gold_ingot
        pf_level_score=bean.level_score
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshHomeEvent(event: RefreshHomeEvent) {
        if (event.isRefresh) {
            mHomeFragment?.lazyLoad()
        }
    }


    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState?.putInt(BOTTOM_INDEX, mIndex)
    }

    /**
     * 展示Fragment
     * @param index
     */
    private fun showFragment(index: Int) {
        val transaction = supportFragmentManager.beginTransaction()
        hideFragments(transaction)
        mIndex = index
        when (index) {
            FRAGMENT_HOME // 首页
            -> {
                //toolbar.title = getString(R.string.app_name)
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.getInstance()
                    transaction.add(R.id.container, mHomeFragment!!, "home")
                } else {
                    transaction.show(mHomeFragment!!)
                }
            }
            FRAGMENT_CLASSROOM  // 课堂
            -> {
               // toolbar.title = getString(R.string.classroom)
                if (mClassroomFragment == null) {
                    mClassroomFragment = ClassroomFragment.getInstance()
                    transaction.add(R.id.container, mClassroomFragment!!, "classroom")
                } else {
                    transaction.show(mClassroomFragment!!)
                }
            }
            FRAGMENT_SWORD // 论剑
            -> {
               // toolbar.title = getString(R.string.sword)
                if (mSwordFragment == null) {
                    mSwordFragment = SwordFragment.getInstance()
                    transaction.add(R.id.container, mSwordFragment!!, "sword")
                } else {
                    transaction.show(mSwordFragment!!)
                }
            }
            FRAGMENT_DISCOVER // 发现
            -> {
                //toolbar.title = getString(R.string.discover)
                if (mDiscoverFragment == null) {
                    mDiscoverFragment = DiscoverFragment.getInstance()
                    transaction.add(R.id.container, mDiscoverFragment!!, "discover")
                } else {
                    transaction.show(mDiscoverFragment!!)
                }
            }
            FRAGMENT_ME // 我
            -> {
                //toolbar.title = getString(R.string.me)
                if (mMeFragment == null) {
                    mMeFragment = MeFragment.getInstance()
                    transaction.add(R.id.container, mMeFragment!!, "me")
                } else {
                    transaction.show(mMeFragment!!)
                }
            }
        }
        transaction.commit()
    }

    /**
     * 隐藏所有的Fragment
     */
    private fun hideFragments(transaction: FragmentTransaction) {
        mHomeFragment?.let { transaction.hide(it) }
        mClassroomFragment?.let { transaction.hide(it) }
        mSwordFragment?.let { transaction.hide(it) }
        mDiscoverFragment?.let { transaction.hide(it) }
        mMeFragment?.let { transaction.hide(it) }
    }

    /**
     * NavigationItemSelect监听
     */
    private val onNavigationItemSelectedListener =
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                return@OnNavigationItemSelectedListener when (item.itemId) {
                    R.id.action_home -> {
                        showFragment(FRAGMENT_HOME)
                        true
                    }
                    R.id.action_classroom -> {
                        showFragment(FRAGMENT_CLASSROOM)
                        true
                    }
                    R.id.action_sword -> {
                        showFragment(FRAGMENT_SWORD)
                        true
                    }
                    R.id.action_discover -> {
                        showFragment(FRAGMENT_DISCOVER)
                        true
                    }
                    R.id.action_me -> {
                        showFragment(FRAGMENT_ME)
                        true
                    }
                    else -> {
                        false
                    }

                }
            }


    private fun goCommonActivity(type: String) {
        Intent(this@MainActivity, CommonActivity::class.java).run {
            putExtra(Constant.TYPE_KEY, type)
            startActivity(this)
        }
    }

    /**
     * 去登陆页面
     */
    private fun goLogin() {
        Intent(this@MainActivity, LoginActivity::class.java).run {
            startActivity(this)
        }
    }

    override fun recreate() {
        try {
            val fragmentTransaction = supportFragmentManager.beginTransaction()
            if (mHomeFragment != null) {
                fragmentTransaction.remove(mHomeFragment!!)
            }
            if (mClassroomFragment != null) {
                fragmentTransaction.remove(mClassroomFragment!!)
            }
            if (mSwordFragment != null) {
                fragmentTransaction.remove(mSwordFragment!!)
            }
            if (mDiscoverFragment != null) {
                fragmentTransaction.remove(mDiscoverFragment!!)
            }
            if (mMeFragment != null) {
                fragmentTransaction.remove(mMeFragment!!)
            }
            fragmentTransaction.commitAllowingStateLoss()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.recreate()
    }

    /**
     * 退出登录 Dialog
     */
    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this@MainActivity, resources.getString(R.string.logout_ing))
    }

    /**
     * Logout
     */
    private fun logout() {
        DialogUtil.getConfirmDialog(this, resources.getString(R.string.confirm_logout),
                DialogInterface.OnClickListener { _, _ ->
                    mDialog.show()
                    mPresenter?.logout()
                }).show()
    }

    override fun showLogoutSuccess(success: Boolean) {
        if (success) {
            doAsync {
                // CookieManager().clearAllCookies()
                Preference.clearPreference()
                uiThread {
                    mDialog.dismiss()
                    showToast(resources.getString(R.string.logout_success))
                    //pf_user_name = pf_username?.text.toString().trim()
                    isLogin = false
                    EventBus.getDefault().post(LoginEvent(false))
                }
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (mIndex != FRAGMENT_CLASSROOM) {
            menuInflater.inflate(R.menu.menu_activity_main, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_search -> {
                Intent(this, SearchActivity::class.java).run {
                    startActivity(this)
                }
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis().minus(mExitTime) <= 2000) {
                finish()
            } else {
                mExitTime = System.currentTimeMillis()
                showToast(getString(R.string.exit_tip))
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        mHomeFragment = null
        mClassroomFragment = null
        mSwordFragment = null
        mDiscoverFragment = null
        mMeFragment = null
    }

}
